<template>
  <div class="password-container">
    <!--  内容区域-->
    <div class="password-form-area">
      <a-form ref="formRef" :model="form" :rules="passwordComplexityEnabledRules" layout="vertical">
        <a-form-item label="原密码" name="old_password">
          <a-input-password class="form-item" v-model:value.trim="form.old_password" type="password" placeholder="请输入原密码" />
        </a-form-item>
        <a-form-item label="新密码" name="new_password">
          <a-input-password class="form-item" v-model:value.trim="form.new_password" type="password" placeholder="请输入新密码" @input="checkPasswordStrength" />
          <div v-if="strengthMessage" :class="strengthClass">
            {{ strengthMessage }}
          </div>
        </a-form-item>
        <a-form-item label="确认密码" name="again_password">
          <a-input-password class="form-item" v-model:value.trim="form.again_password" type="password" placeholder="请输入确认密码" @input="checkPasswordStrengthed" />
          <div v-if="strengthMessaged" :class="strengthClassed">
            {{ strengthMessaged }}
          </div>
        </a-form-item>
      </a-form>
      <a-button type="primary" style="margin: 20px 0 0 250px" @click="onSubmit">修改密码</a-button>
    </div>
  </div>
</template>
<script setup lang="ts">
import { reactive, ref } from 'vue'
import { message } from 'ant-design-vue'
import { accountApi } from '@/api/business/account/account-api'
import { useLoadingStore } from '@/store/modules/loading-store'
import { errorSentry } from '@/lib/error-sentry'
const loadingStore = useLoadingStore()

const emits = defineEmits(['onSuccess'])
const strengthClass = ref('')
const strengthClassed = ref('')
const strengthMessage = ref('')
const strengthMessaged = ref('')
const formRef = ref()

const passwordComplexityEnabledRules = {
  old_password: [{ required: true, message: '请输入原密码' }],
  new_password: [{ required: true, message: '密码格式错误' }],
  again_password: [
    { required: true, message: '请输入确认密码' },
    {
      asyncValidator: async (_, val, callback) => {
        const { new_password } = form
        if (val !== new_password) {
          callback(new Error('确认新密码与新密码不一致'))
        } else {
          callback()
        }
      }
    }
  ]
}

const formDefault = {
  old_password: '',
  new_password: ''
}
const form = reactive({
  ...formDefault
})
// 密码强度检查
const checkPasswordStrength = () => {
  // 修复后的弱密码规则
  const weakRegex = /^(?=.*[\d])[A-Za-z\d]{6,}$/
  const mediumRegex = /^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*\d))|((?=.*[a-z])(?=.*\d))).*$/
  const strongRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/

  if (!form.new_password) {
    strengthMessage.value = '请输入密码'
    strengthClass.value = 'text-gray' // 灰色
  } else if (strongRegex.test(form.new_password)) {
    strengthMessage.value = '强'
    strengthClass.value = 'text-green' // 绿色
  } else if (mediumRegex.test(form.new_password)) {
    strengthMessage.value = '中'
    strengthClass.value = 'text-yellow' // 黄色
  } else if (weakRegex.test(form.new_password)) {
    strengthMessage.value = '弱'
    strengthClass.value = 'text-red' // 红色
  } else {
    strengthMessage.value = '密码不符合要求，请至少包含6位字符'
    strengthClass.value = 'text-gray' // 灰色
  }
}
const checkPasswordStrengthed = () => {
  // 修复后的弱密码规则
  const weakRegex = /^(?=.*[\d])[A-Za-z\d]{6,}$/
  const mediumRegex = /^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*\d))|((?=.*[a-z])(?=.*\d))).*$/
  const strongRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/

  if (!form.again_password) {
    strengthMessaged.value = '请输入密码'
    strengthClassed.value = 'text-gray' // 灰色
  } else if (strongRegex.test(form.again_password)) {
    strengthMessaged.value = '强'
    strengthClassed.value = 'text-green' // 绿色
  } else if (mediumRegex.test(form.again_password)) {
    strengthMessaged.value = '中'
    strengthClassed.value = 'text-yellow' // 黄色
  } else if (weakRegex.test(form.again_password)) {
    strengthMessaged.value = '弱'
    strengthClassed.value = 'text-red' // 红色
  } else {
    strengthMessaged.value = '密码不符合要求，请至少包含6位字符'
    strengthClassed.value = 'text-gray' // 灰色
  }
}

async function onSubmit() {
  formRef.value
    .validate()
    .then(async () => {
      if (form.new_password !== form.again_password) {
        message.error('新密码与确认密码不一致')
        return
      }
      loadingStore.show()
      try {
        await accountApi.queryChangePassword(form)
        message.success('修改成功')

        form.old_password = ''
        form.new_password = ''
        form.again_password = ''
        strengthMessage.value = ''
        strengthClass.value = ''
        strengthMessaged.value = ''
        strengthClassed.value = ''

        emits('onSuccess')
      } catch (error) {
        message.error(error.msg)
        errorSentry.captureError(error)
      } finally {
        loadingStore.hide()
      }
    })
    .catch((error) => {
      console.log('error', error)
      message.error('参数验证错误，请仔细填写表单数据!')
    })
}
</script>
<style lang="less" scoped>
.password-container {
  .header-title {
    font-size: 20px;
  }

  .password-form-area {
    margin-top: 30px;
    .text-green {
      color: #2ecc71; /* 绿色 */
    }

    .text-yellow {
      color: #f1c40f; /* 黄色 */
    }

    .text-red {
      color: #e74c3c; /* 红色 */
    }

    .text-gray {
      color: #999; /* 灰色 */
    }
    .form-item {
      width: 550px !important;
    }
  }
}
</style>
